package it.java.giw.dataextraction.aleph.helper;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class CSVHelper {
	
	public CSVHelper (){
		
	}
	
	public List<String[]> readCsv(String filename, char delimiter) throws Exception {
		List<String[]> ret = new ArrayList<String[]>();

		File f = new File(filename);
		FileReader fr = new FileReader(f);
		List<String[]> l;
		CSVReader csvReader;
		Iterator<String[]> iter;
		csvReader = new CSVReader(fr, delimiter);
		l = csvReader.readAll();
		iter = l.iterator();
		while(iter.hasNext()) {
			String[] row = (String[]) iter.next();
			ret.add(row);
		}
		csvReader.close();
		fr.close();
		return ret;
	}
	
	public synchronized void writeCSV(String[] info, String name) throws Exception {
		File fn = null;
		fn = new File(name);
		FileWriter fw;
		CSVWriter resultCsvWriter;
		fw = new FileWriter(fn, true);		
		resultCsvWriter = new CSVWriter(fw, '\t');
		String[] out = new String[info.length];
		for(int i=0; i<info.length; i++){
			out[i] = info[i];
		}
		resultCsvWriter.writeNext(out);
		resultCsvWriter.close();
		fw.close();
	}
}
